
angular.module('U9ImHd.utility')

    .factory('Help', ['$ocLazyLoad', '$ionicHistory', '$state', 'Config', 'APPCONSTANTS', 
        function ($ocLazyLoad, $ionicHistory, $state, Config, APPCONSTANTS) {
            var o = {};

            o.getAppFileDir = function () {
                return cordova.file.externalRootDirectory || cordova.file.dataDirectory;
            };
            o.getConfigDir = function () {
                return o.getAppFileDir() + '/' + APPCONSTANTS.appID + '/';
            };
            o.getAppsDir = function () {
                return o.getConfigDir() + 'apps/';
            };
            o.getFullPath = function (src, appId) {
                return getFullPath (src, appId);
            };
            o.getFullURL = function (url) {
                if (!url) {
                    return null;
                }
                var address = Config.get('address', APPCONSTANTS.defaultAddress),
                    port = Config.get('port', APPCONSTANTS.defaultPort);
                if (url[0] !== '\/') {
                    url = '\/' + url;
                }
                return 'http://' + address + ':' + port + url;
            };
            o.loadApp = function (appId) {
                return $ocLazyLoad.load({
                    name: appId,
                    files: [
                        getFullPath('js/main.js', appId),
                        getFullPath('css/main.css', appId)
                    ]
                });
            };
            o.goAsRoot = function (state, animate) {
                $ionicHistory.nextViewOptions({
                    historyRoot: true,
                    disableAnimate: !animate,
                    expire: 300
                });
                $state.go(state);
            };

            return o;

            function getFullPath (src, appId) {
                var childAppRootDir = '';
                src = appId + '/' + src;
                if (window.cordova && cordova.file) {
                    childAppRootDir = o.getConfigDir() + 'apps/';
                } else {
                    src = 'wwws/' + src;
                }
                return childAppRootDir + src;
            }
        }
    ]);